package com.falm.maker.generator.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Objects;

/**
 * @author Administrator
 */
public class StaticFileGenerator extends FileGenerate {
    public static final Logger logger = LoggerFactory.getLogger(StaticFileGenerator.class);

    @Override
    public void doGenerate(String inputPath, String outputPath){
        copyFilesByHutool(inputPath, outputPath);
    }

    /**
     * 根据hutool复制文件
     *
     * @param inputPath  输入文件路径
     * @param outputPath 输出文件路径
     */
    public static void copyFilesByHutool(String inputPath, String outputPath) {
        FileUtil.copy(inputPath, outputPath, true);
    }

    public static void copyFileByCustom(String inputPath, String outputPath) {
        File ori = new File(inputPath);
        File desc = new File(outputPath + File.separator + ori.getName());
        if (ObjectUtil.isEmpty(ori)) {
            logger.info("源文件不存在");
        }
        if (ori.isDirectory()) {
            // 如果源路径是文件夹
            if (!desc.exists()) {
                // 如果目标路径不存在，则先创建文件夹
                if (desc.mkdirs()) {
                    logger.info("创建文件夹成功");
                } else {
                    logger.info("创建文件夹失败");
                }
            }
            copyFolder(ori, desc);
        } else {
            copyFile(ori, desc);
        }
    }

    /**
     * 文件复制
     *
     * @param ori  源文件路径
     * @param desc 目标文件路径
     */
    private static void copyFile(File ori, File desc) {
        byte[] buf = new byte[1024 * 8];
        int len;
        try (FileInputStream fis = new FileInputStream(ori); FileOutputStream fos = new FileOutputStream(desc)) {
            while ((len = fis.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void copyFolder(File inputPath, File outputPath) {
        if (!outputPath.exists()) {
            if (!outputPath.mkdir()) {
                logger.error("创建目录失败");
            }
        }
        for (String s : Objects.requireNonNull(inputPath.list())) {
             File file = new File(inputPath, s);
             File desc = new File(outputPath, s);
            if (file.isFile()) {
                copyFile(file, desc);
            } else {
                copyFolder(file, desc);
            }
        }
    }

}
